﻿using System;
using System.Web.Mvc;
using Inscriptionem.Models.Enums;
using Inscriptionem.Models.Requests;
using Inscriptionem.Models.Views;
using Inscriptionem.Services;

namespace Inscriptionem.Controllers
{
    public class InstallController : Controller
    {
        #region Install
        public ActionResult Index()
        {
            if (InstallService.IsDBAvailableAndCorrect)
            {
                return View("Ready");
            }

            return View("Index", new InstallViewModel() {IsRealNameVisible = true});
        }

        [HttpPost()]
        public ActionResult Index(InstallRequestModel model)
        {
            ViewResult result = null;

            var viewModel = InstallService.ValidateInstallRequest(model);
            if (viewModel.Error == InstallError.None)
            {
                try
                {
                    if (InstallService.Install(model))
                    {
                        result = View("Ready");
                        InstallService.Restart();
                    }
                }
                catch (Exception ex)
                {
                    viewModel.Error = InstallError.Other;
                }
            }

            return result ?? View("Index", viewModel);
        }

        #endregion

        #region Maintenance
        public ActionResult Maintenance()
        {
            return View();
        }
        #endregion
    }
}
